// pages/scenicBuy/scenicBuy.js
import Toast from '../../dist/toast/toast';
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    app:app,
    curInfo:{},
    curTicketInfo:"",
    curSwipers:[],

    showTitle:false,
    poppable:false,
    minDate: new Date(2024, 2, 9).getTime(),
    maxDate: new Date(2024, 2, 30).getTime(),
    showconfirm:false,

    dateQuicks:[{str:"今天03-22",state:"入住",date:"2024-05-13",price:10,select:false,border:""},{str:"今天03-22",
    state:"离店",price:10,select:false},{str:"今天03-22",price:10,select:false}],
    curSelectDate:{},
    disableInput:true,
    infoWarning1:false,
    infoWarning2:false,
    infoWarning3:false,
    inputTxt1:"",
    inputTxt2:"",
    inputTxt3:"",
    testFlag:true,
    myscroll:null,
    isPayDetailShow:false,
    isCouponShow:false,
    isTipsShow:false,
    isShowCal:false,//是否显示日历
    curYear:0,
    curMonth:4,
    curDate:0,
    formatter:null,
    selectIdxs:[],
    rangeDate:[],
    curPrice:0,
    totalPrice:0,
    curNum:1
  },
  formatter2(day) {
    const year = day.date.getFullYear();
    const month = day.date.getMonth();
    const date = day.date.getDate();
    const _this = this;
    //console.log("=====",this);
    const rangeDate = _this.data.rangeDate;
    if(rangeDate.length > 0){
      const date1 = new Date(rangeDate[0]);
      const date2 = new Date(rangeDate[1]);
      if(year == date1.getFullYear() && month == date1.getMonth() && date == date1.getDate()){
          day.topInfo = '入住';
          //day.bottomInfo = '';//+_this.data.curInfo.oldPrice;
      }
      else if(year == date2.getFullYear() && month == date2.getMonth() && date == date2.getDate()){
        day.topInfo = '离店';
        //day.bottomInfo = '';//+_this.data.curInfo.oldPrice;
      }
    }
    day.bottomInfo = '';
    //day.bottomInfo = ''+_this.data.curInfo.price;
    //day.bottomInfoStyle = {line:"none",color:"red"};
    return day;
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.setNavigationBarTitle({
      title: '酒店预定',
    })
    try{
      const info = JSON.parse(options.data);

      this.setData({curTicketInfo:options.data,curInfo:info,curSwipers:info.swipers});
      var qs = this.data.dateQuicks;
      for(var i=0; i<qs.length; i++){
        qs[i].price = info.price;
      }
      this.setData({formatter:this.formatter2,dateQuicks:qs});
    }
    catch(e){
      console.warn("ticketsBuy.js报错");
    }

    var oneday = 86400*1000;
    var date = new Date();
    var date2 = new Date();
    date2.setTime(date2.getTime() + oneday);
    this.initDateInfo(date, date2);
    this.onDateClick(null, [0,1]);

    /**wx.createSelectorQuery()
    .select('#myscroll')
    .node()
    .exec((res) => {
      var scrollView = res[0].node;
      this.setData({myscroll:scrollView});
      console.log(scrollView);
      //scrollView.scrollEnabled = false;
    })**/
  },
  onCalLeftClick(){
    this.data.curMonth --;
    console.log("left click,month=" + this.data.curMonth);
    this.setCalView(this.data.curYear, this.data.curMonth, this.data.curDate);
  },
  onCalRightClick(){
    this.data.curMonth ++;
    console.log("right click,month=" + this.data.curMonth);
    this.setCalView(this.data.curYear, this.data.curMonth, this.data.curDate);
  },
  onCalClose(e){
    this.setData({isShowCal:false});
  },
  onCalConfirm(e){
    const [start, end] = e.detail;
    var date = new Date(start);
    var date2 = new Date(end);
    const times = [date.getTime(), date2.getTime()];
    console.log("日期="+e.detail);
    this.initDateInfo(date, date2);
    this.onDateClick(null, [0,1]);
    this.setData({
      isShowCal:false,
      rangeDate: times
    });
    console.log("肯定是", this.data.rangeDate);
  },
  formatDate(date) {
    date = new Date(date);
    return `${date.getMonth() + 1}/${date.getDate()}`;
  },
  onDateClick2(e){
    var date = new Date();
    const curYear = date.getFullYear();
    const curMonth = date.getMonth();
    const curDate = date.getDate();
    this.data.curYear = curYear;
    this.data.curMonth = curMonth;
    this.data.curDate = curDate;


    this.setCalView(curYear, curMonth, curDate);
    this.setData({
      isShowCal:!this.data.isShowCal
    });
    if(this.data.rangeDate.length <= 0){
      var oneday = 86400*1000;
      const time = date.getTime();
      const times = [time, time+oneday];
      this.setData({
        rangeDate:times
      });
    }
  },
  setCalView(curYear,curMonth,curDate){
    var dateStart = new Date(curYear, curMonth, curDate);
    var temp = new Date(curYear, curMonth+1, 0);
    var dateEnd = new Date(curYear, curMonth, temp.getDate());
    console.log("day="+dateEnd.getDate());

    var date = new Date();
    const cy = date.getFullYear();
    const cm = date.getMonth();
    const cd = date.getDate();

    var minDate = null;
    var maxDate = dateEnd.getTime();
    if(curYear > cy || curMonth > cm){
      minDate = new Date(curYear, curMonth, 1).getTime();
    }
    else if(curYear < cy || curMonth < cm){
      minDate = maxDate;
      maxDate -= 86400*900;
    }
    else{
      minDate = dateStart.getTime();
    }
    //minDate = dateEnd.getTime() + 86400*1000;
    //maxDate = dateEnd.getTime();

    this.setData({
      minDate:minDate,
      maxDate:maxDate
    });
  },
  onDateClick(e, indexs=null){
    var quicks = this.data.dateQuicks;
    //console.log(e);
    var idxs = this.data.selectIdxs;
    if(indexs != null){
      idxs = indexs;
    }
    else{
      if(idxs.length >= 2){
        idxs.length = 0;
      }
      idxs.push(e.currentTarget.dataset.idx);
      this.setData({selectIdxs:idxs});
    }
    var curDate = null;
    const states = ["入住","离店"];
    var stateIndex = 0;
    const timeArr = [];
    for(var i=0; i<quicks.length; i++){
      if(idxs.indexOf(i) != -1){
        quicks[i].border = "2rpx solid rgb(51, 153, 255)";
        quicks[i].select = true;
        curDate = quicks[i];
        quicks[i].state = states[stateIndex];
        stateIndex ++;
        timeArr.push(quicks[i].time);
      }
      else{
        quicks[i].state = "";
        quicks[i].border = "2rpx solid rgba(17, 17, 17, 0.562)";
        quicks[i].select = false;
      }
    }
    var curPrice = 0;
    if(stateIndex >= 2){
      var oneday = 86400*1000;
      var start = Math.floor(timeArr[0] / oneday) * oneday;
      var end = Math.floor(timeArr[1] / oneday) * oneday;
      while(start < end){
        curPrice += this.data.curInfo.price;
        start += oneday;
      }
    }
    this.setData({dateQuicks:quicks,curSelectDate:curDate,curPrice:curPrice,rangeDate:timeArr});
    this.refreshPrice();
  },
  onStepChange(e){
    const num = e.detail;
    this.setData({curNum:num});
    this.refreshPrice();
  },
  refreshPrice(){
    var totalPrice = this.data.curPrice * this.data.curNum;
    this.setData({totalPrice:totalPrice});
  },
  initDateInfo(date1, date2){
    var oneday = 86400*1000;
    var curDate = new Date();
    var curDate2 = new Date();
    curDate2.setTime(curDate.getTime() + oneday);
    var quicks = this.data.dateQuicks;
    var tag1,tag2,tag3;
    if(date1.getMonth() == curDate.getMonth() && date1.getDate() == curDate.getDate()
      && date2.getMonth() == curDate2.getMonth() && date2.getDate() == curDate2.getDate()
    ){
      tag1 = "今天";
      tag2 = "明天";
      tag3 = "后天";
    }
    else{
      tag1 = tag2 = tag3 = "";
    }
    var str1 = tag1 + this.getDateStr(date1);
    //quicks[0].border = "2rpx solid rgb(51, 153, 255)";
    quicks[0].str = str1;
    quicks[0].date = this.getDateStr2(date1);
    quicks[0].time = date1.getTime();

    str1 = tag2 + this.getDateStr(date2);
    quicks[1].str = str1;
    quicks[1].date = this.getDateStr2(date2);
    quicks[1].time = date2.getTime();

    date2.setTime(date2.getTime()+oneday);
    str1 = tag3 + this.getDateStr(date2);
    quicks[2].str = str1;
    quicks[2].date = this.getDateStr2(date2);
    quicks[2].time = date2.getTime();
    this.setData({dateQuicks:quicks});
  },
  getDateStr(date){
    var month = date.getMonth() + 1;
    if(month < 10){ month = "0"+month; }
    var day = date.getDate();
    if(day < 10){ day = "0"+day; }
    return month + "-" + day;
  },
  getDateStr2(date){
    var year = date.getFullYear();
    if(year < 10){ year = "0"+year; }
    var month = date.getMonth() + 1;
    if(month < 10){ month = "0"+month; }
    var day = date.getDate();
    if(day < 10){ day = "0"+day; }
    return year + "-" + month + "-" + day;
  },
  onTipsClick(e){
    this.setData({
      isTipsShow:!this.data.isTipsShow
    });
  },
  onNotesEvent(e){
    //console.log(e);
    // if(e.detail.type == "close"){
    //   this.setData({isTipsShow:false});
    // }
    var curInfo = this.data.curInfo;
    var swipers = curInfo.swipers;
    curInfo = JSON.stringify(curInfo);
    //console.log(curInfo);
    this.setData({curTicketInfo:curInfo,curSwipers:swipers});
    this.setData({isTipsShow:!this.data.isTipsShow});
  },
  onTipsViewClick(e){
    this.setData({
      isTipsShow:false
    });
  },
  onCouponClick(e){
    this.setData({
      isCouponShow:!this.data.isCouponShow
    });
  },
  onCouponViewClick(e){
    console.log(e);
    if(e.target.id != "coupon2"){
      this.setData({
        isCouponShow:false
      });
    }
  },
  onPayDetail(e){
    this.setData({
      isPayDetailShow:!this.data.isPayDetailShow
    });
  },
  onPayDetailClick(e){
    this.setData({
      isPayDetailShow:false
    });
  },
  onInputName(e){
    const value = e.detail.value;
    this.setData({inputTxt1:value});
  },
  onInputIcard(e){
    const value = e.detail.value;
    this.setData({inputTxt2:value});
  },
  onInputPhone(e){
    const value = e.detail.value;
    this.setData({inputTxt3:value});
  },
  onPayClick(e){
    var war1 = this.data.inputTxt1 != "" ? false : true;
    var war2 = this.data.inputTxt2 != "" ? false : true;
    var war3 = this.data.inputTxt3 != "" ? false : true;

    if(this.data.rangeDate.length < 2){
      Toast("请完整选择入住、离店日期");
      return;
    }

    if(!war1 && !war2 && !war3){
      //加入订单
      console.log("------------>");
      Toast("已提交订单，请前往我的->我的订单 页面查看");
      const app = getApp();
      const info = this.data.curInfo;
      const curdata = {
        type:"setOrderHotels",
        openid:app.globalData.openid,
        id:info.id,
        name:info.name,
        icon:info.icon,
        num:this.data.curNum,
        price:this.data.curPrice,
        totalPrice:this.data.totalPrice,
        time:new Date().getTime(),
        rangeDate:this.data.rangeDate,
        regInfo:{
          name:this.data.inputTxt1,
          icard:this.data.inputTxt2,
          phone:this.data.inputTxt3
        }
      }
      console.log("酒店预定：",curdata);//
      wx.cloud.callFunction({
        name: 'quickstartFunctions',
        data:curdata,
        complete: res => {
          console.log('setOrderHotels: ', res);
        }
      })
    }
    this.setData({
      infoWarning1:war1,
      infoWarning2:war2,
      infoWarning3:war3
    });

    /**this.data.myscroll.scrollTo({
      top:50,
      left:0
    });**/
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})